<?php
/**
 * Created by PhpStorm .
 * User: {Administrator}
 * Date: {2022/7/6 16:37}
 * Author: '树叶'
 * Email: 'ayunu@qq.com'
 * Motto Info: '理想如果不向现实做一点点屈服，那么理想也将归于尘土。'
 */

namespace app\api\model;
use think\Db;
use think\Model;
use app\api\model\GoodsItem as GoodsItemModel;
use app\api\model\Config as ConfigModel;
use app\api\model\User as UserModel;

class Goods extends Model
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $resultSetType = 'collection';
    // 追加属性
    protected $append = [

    ];


    /**
     * 商品详情
     * $user 用户信息
     * $is_vip 会员级别 0 = 普通用户 1 = 安装店 2 = 代理商 3 = 一级代理
     * $gid   商品id
     */
    public function getGoodsDetail($user = [],$gid)
    {
        $result = [
            'data' => [],
            'status' => false,
            'msg'   => ''
        ];

        $goods = Db::name('goods')
            ->field('id,installation,parameter,brand_id,name,main_image,
                    shuff_image,spec_type,goods_video,attr_json,details_content,is_match,
                    parameter,ordinaryprice,haveprice,agentprice,integral_num,freight,free_shipping')
            ->where('id',$gid)
            ->where('status',0)
            ->find();

        $goods['sc_status'] = 0;
        if (!$goods)
        {
            $result['msg'] = '商品已下架';
            return $result;
        }

        $vehicleList = Db::name('goods_addcategory')->where('gid',$goods['id'])->column('vehicle_id');
        $vehicleList = array_unique($vehicleList);

        $goods['models_id'] = empty($vehicleList) ? 0 : implode(',',$vehicleList);

        // 商品有没有收藏
            if ($user['data'])
            {
                $relation = GoodsRelation::where('uid', $user['data']['id'])
                    ->where('gid',$gid)
                    ->where('type','collect')
                    ->find();
                $goods['sc_status'] = empty($relation) ? 0 : 1;
            }

        if ($user['data'])
        {
            UserHistory::addHistory($user['data']['id'],$gid); // 添加浏览记录
        }

        if ($goods['spec_type'] == 1)
        {
            $attr_json = json_decode($goods['attr_json'],true);
        }
        $ConfigModel = new ConfigModel();
        $Agente      = $ConfigModel->getAgent();
        $OneAgent    = $ConfigModel->getOneAgent();
        if ($user['is_vip'] == 0)
        {
            $goods['price'] = $goods['ordinaryprice'];
        }elseif($user['is_vip'] == 1){
            $goods['price'] = empty($goods['agentprice']) || $goods['agentprice'] == 0 ? $goods['haveprice'] : $goods['agentprice'];
        }elseif($user['is_vip'] == 2){
            if($user['data']['is_price'] == 1)
            {
                $goods['price']  = empty($goods['agentprice']) || $goods['agentprice'] == 0 ? bcmul($Agente, $goods['haveprice'], 2) : $goods['agentprice'];
            }else{
                $goods['price'] = empty($goods['agentprice']) || $goods['agentprice'] == 0 ? $goods['haveprice'] : $goods['agentprice'];
            }
        }elseif ($user['is_vip'] == 3){
            if($user['data']['is_price'] == 1)
            {
                $goods['price']  = empty($goods['agentprice']) || $goods['agentprice'] == 0 ? bcmul($OneAgent, $goods['haveprice'], 2) : $goods['agentprice'];
            }else{
                $goods['price'] = empty($goods['agentprice']) || $goods['agentprice'] == 0 ? $goods['haveprice'] : $goods['agentprice'];
            }
        }

        $goods['attr_json'] = empty($attr_json) ? [] : $attr_json;

        foreach ($goods['attr_json'] as $key => $val)
        {
            $goods['attr_json'][$key]['values'] = explode(',', $val['values']);
        }

        $result['msg']    = '获取成功';
        $result['status'] = true;
        $result['data']   = $goods;
        return $result;
    }

    /**
     * 商品列表
     */
    public function Getgoodslist($name = '',$uid = '', $limit = 20, $page = 1, $sales_sum, $order_price,$high_price = '',$low_price = '',$cartgory = 0)
    {
        $where = [];
        $where['status'] = ['eq', 0];
        $usermodel = new UserModel();
        $userdata = $usermodel->getUserInfo($uid);
        $user = $userdata['data'];

        if (!empty($user['cartype']))
        {
            // 车型信息
            $userCar = UserModel::userCar($user['cartype']);
        }
        $fieldinset = '';
        if ($cartgory)
        {
            $cartgoryList= Db::name('goods_addcategory')
                ->field('gid,category_id,vehicle_id')
                ->where('category_id',$cartgory)
                ->select();
            $goodsId = [];
            foreach($cartgoryList as $cartgoryKey => $cartgoryVal)
            {
                if (empty($userCar))
                {
                    if (!in_array($cartgoryVal['gid'],$goodsId))
                    {
                        $goodsId[] = $cartgoryVal['gid'];
                    }
                }else{
                    if (in_array($cartgoryVal['vehicle_id'],$userCar) || $cartgoryVal['vehicle_id'] == 0 )
                    {
                        if (!in_array($cartgoryVal['gid'],$goodsId))
                        {
                            $goodsId[] = $cartgoryVal['gid'];
                        }
                    }
                }
            }
            if (!empty($goodsId))
            {
                $where['id'] = ['in',$goodsId];
            }
        }else{

            if (!empty($userCar))
            {
                foreach($userCar as $k => $v){
                    $fieldinset .= "FIND_IN_SET('$v',models_id) OR ";
                }
                $fieldinset = substr($fieldinset,0,-3);
            }
        }

            $ConfigModel = new ConfigModel();
            $Agente      = $ConfigModel->getAgent();
            $OneAgent    = $ConfigModel->getOneAgent();
            if ($userdata['is_vip'] == 0 )
            {
                $file = 'id,name,models_id,ordinaryprice,haveprice,agentprice,main_image,status,sales, ordinaryprice as price';
            }elseif ($userdata['is_vip'] == 1)
            {
                $file = 'replacenum,models_id,name_keyword,id,name,goods_number,partnumber,ordinaryprice,haveprice,agentprice,main_image,status,sales,(case when agentprice > 0 then agentprice else haveprice end) as price';
            }elseif ($userdata['is_vip'] == 2 && $userdata['data']['is_price'] == 1){
                $file = 'id,name,ordinaryprice,haveprice,agentprice,main_image,status,sales,
                (case when agentprice > 0 then agentprice else convert(haveprice * '.$Agente.', decimal(10,2)) end) as price';
            }elseif ($userdata['is_vip'] == 3 && $userdata['data']['is_price'] == 1){
                $file = 'replacenum, name_keyword,id,name,ordinaryprice,partnumber,goods_number,haveprice,agentprice,main_image,status,sales,
                (case when agentprice > 0 then agentprice else convert(haveprice * '.$OneAgent.', decimal(10,2)) end) as price';
            }elseif ($userdata['is_vip'] == 2 || $userdata['is_vip'] == 3){
                $file = 'replacenum, name_keyword,id,name,ordinaryprice,partnumber,goods_number,haveprice,agentprice,main_image,status,sales,(case when agentprice > 0 then agentprice else haveprice end) as price';
            }

        $order_by = '';
        if ($order_price == 1)
        {
            $order_by = "price desc";
        }
        if ($order_price == 2)
        {
            $order_by = "price asc";
        }
        $replace  = "";
        $find_set = "";

        if ($name)
        {
            $nameId = Db::name('brand')->where('name',$name)->value('id');

            if ($nameId)
            {
                $find_set = "FIND_IN_SET($nameId,brand_id)";
            }else{
                $name = explode(" ",$name);
                $replace = [];
                foreach ($name as $item)
                {
                    $replace[] = '%'.$item.'%';
                }

                $where['name|goods_number|name_keyword|replacenum|models_name|manufacturer'] = ['like',$replace, 'OR' ];
            }
        }

        if ($sales_sum)
        {
            // 销量排序
            if ($order_by)
            {
                $order_by = $order_by." sales desc";
            }else{
                $order_by = "sales desc";
            }
        }

        if ($high_price && $low_price)
        {
            $where['ordinaryprice'] = [
                ['gt',$low_price],['lt',$high_price]
            ];
        }elseif ($high_price)
        {
            $where['ordinaryprice'] = ['<',$high_price];
        }elseif ($low_price){
            $where['ordinaryprice'] = ['>',$low_price];
        }

        $list = Db::name('goods')
            ->field($file)
            ->where($find_set)
            ->where($where)
            ->order($order_by)
            ->where($fieldinset)
            ->paginate($limit, false, ['page' => $page]);

        return $list;
    }

    /**
     * 添加收藏
     */
    public function addrelation($data)
    {
        if (empty($data['uid']) || empty($data['gid']))
        {
            return false;
        }
        $response = Db::name('goods_relation')->insert($data);
        if (!$response) return false;
        return true;
    }

    /**
     * 收藏列表
     */
    public function Getgoodsrelation($uid, $limit, $page, $category = '',$name = '')
    {
        $UserModel = new UserModel();
        $userinfo = $UserModel->getUserInfo($uid);

        if (!$userinfo['data']) return false;

        $data = Db::name('goods_relation')
            ->where('uid',$uid)
            ->order('create_time desc')
            ->paginate($limit, false, ['page' => $page]);

        $ConfigModel = new ConfigModel();
        $agent = $ConfigModel->getAgent();
        $OneAgent = $ConfigModel->getOneAgent();
        $list  = $data->items();
        $count = $data->total();
        foreach($list as $k => $v)
        {
            $list[$k]['create_time']  = date('Y-m-d',$v['create_time']);
            $where['id'] = ['eq',$v['gid']];
            $where['status'] = ['eq',0];
            if ($category)
            {
                $where['category_id'] = ['eq',$category];
            }
            if ($name)
            {
                $where['name']  = ['like','%'.$name.'%'];
            }
            $goodslist = Db::name('goods')
                ->field('name,main_image,ordinaryprice,haveprice,agentprice')
                ->where($where)
                ->find();
            if (!$goodslist)
            {
                unset($list[$k]);
                continue;
            }
            if ($userinfo['is_vip'] == 0)
            {
                $goodslist['price'] = $goodslist['ordinaryprice'];
            }
            if ($userinfo['is_vip'] == 1)
            {
                $goodslist['price'] = $goodslist['agentprice'] == 0 ? $goodslist['agentprice'] : $goodslist['haveprice'];
            }
            if ($userinfo['is_vip'] == 2)
            {

                $goodslist['price'] = $goodslist['agentprice'] == 0 ? $goodslist['haveprice'] * $agent : $goodslist['agentprice'];
            }
            if ($userinfo['is_vip'] == 3)
            {

                $goodslist['price'] = $goodslist['agentprice'] == 0 ? $goodslist['haveprice'] * $OneAgent : $goodslist['agentprice'];
            }

            $list[$k]['goods'] = $goodslist;
        }
        $list = array_values($list);

        $res = [
            'list'  => $list,
            'count' => $count
        ];
        return $res;
    }

    /**
     * 删除收藏
     */
    public function Getrelationdel($uid,$ids = '',$type = 0)
    {
        if ($type)
        {
            return Db::name('goods_relation')->where('uid',$uid)->delete();
        }else{
            return Db::name('goods_relation')->where('id','in',$ids)->delete();

        }
    }

    /**
     *  商品组合
     */
    public function Getcombination($id,$userInfo)
    {
        if (!$id) return false;

        $colloction = Db::name('goods_collocation')
            ->where('goods_id', $id)
            ->order('id desc')
            ->limit(1)
            ->select();
        if (empty($colloction))
        {
            return false;
        }
        if ($colloction[0]['child_goods_sku'] == 0)
        {
            $goods = Goods::where('id',$colloction[0]['child_goods_id'])
                ->field('ordinaryprice,haveprice,agentprice')
                ->find();
        }else{
            $goods = GoodsItemModel::where('goods_id',$colloction[0]['goods_id'])
                ->where('id',$colloction[0]['child_goods_sku'])
                ->field('ordinaryprice,haveprice,haveprice')
                ->find();
        }
        $ConfigModel = new ConfigModel();
        $Agent    = $ConfigModel->getAgent();
        $OneAgent = $ConfigModel->getOneAgent();

        switch($userInfo['is_vip'])
        {
            case 0:
            $colloction[0]['price'] = $goods['ordinaryprice'];
            break;
            case 1:
            $colloction[0]['price'] = $goods['agentprice'] != 0 ? $goods['agentprice'] : $goods['haveprice'];
            break;
            case 2:
                if ($userInfo['data']['is_price'] == 1)
                {
                    $colloction[0]['price'] = $goods['agentprice'] != 0 ? $goods['agentprice'] : bcmul($Agent, $goods['haveprice'], 2);
                }else{
                    $colloction[0]['price'] = $goods['agentprice'] != 0 ? $goods['agentprice'] : $goods['haveprice'];
                }
            break;
            case 3:
                if ($userInfo['data']['is_price'] == 1)
                {
                    $colloction[0]['price'] = $goods['agentprice'] != 0 ? $goods['agentprice'] : bcmul($OneAgent, $goods['haveprice'], 2);
                }else{
                    $colloction[0]['price'] = $goods['agentprice'] != 0 ? $goods['agentprice'] : $goods['haveprice'];
                }
            break;

         }
        $Res = !empty($colloction) ? $colloction : [];
        return $Res;
    }

    /**
     * 热门推荐
     */
    public function Getgoodshot($userInfo = [])
    {
        $where = [];
        $where['status'] = ['eq',0];

        // 如果未登录或者未绑定车型
        $uid = empty($userInfo['data']['id']) ? 0 : $userInfo['data']['id'];
        if (empty($userInfo) || empty($userInfo['data']['cartype']))
        {
             $list = Db::name('goods')
                ->field('id,name,ordinaryprice,haveprice,agentprice,main_image')
                ->where('status',0)
                ->where('is_hot',1)
                ->order('is_hot desc,sales desc')
                ->select();

        }else{
            // 查看绑定车型
            $userCar = UserModel::userCar($userInfo['data']['cartype']);
            $vehicle_id = [];
            if($userCar){
                foreach($userCar as $key => $val){
                    $vehicle_id[] = $val;
                }
            }
            $addcategory = Db::name('goods_addcategory')
                ->distinct(true)
                ->field('gid')
                ->where('vehicle_id','in',$vehicle_id)
                ->select();
            $list = [];
            foreach ($addcategory as $value){
                 $list[] = Db::name('goods')
                    ->field('id,name,ordinaryprice,haveprice,agentprice,main_image')
                    ->where('id',$value['gid'])
                    ->where('is_hot',1)
                    ->where('status',0)
                    ->find();
            }
        }
        if(is_array($list))
        {

            $list = Db::name('goods')
                ->field('id,name,ordinaryprice,haveprice,agentprice,main_image')
                ->where('status',0)
                ->order('is_hot desc,sales desc')
                ->select();
        }

        $list = UserModel::goodsprice($uid,$list);

        return $list;
    }

    /**
     * 新品推荐
     */
    public function getIsnew($uid,$page,$limit,$name = '',$category = '')
    {
        $userModel = new UserModel();
        $userInfo = $userModel->getUserInfo($uid);

        if (empty($userInfo)) return false;

        $field = 'id,name,ordinaryprice,haveprice,agentprice,main_image';
        $where = [];

        if ($name)
        {
            $where['name'] = ['like','%'.$name.'%'];
        }
        $order = 'sales desc';
        if (!empty($userInfo['data']['cartype']))
        {
            $usercar = $userModel->userCar($uid);
                $map = [];
                $usercar = array_values($usercar);
                $map['vehicle_id'] = array(['in',$usercar],['eq',0],'or');
                if (!empty($category))
                {
                    $map['category_id'] = ['eq',$category];
                }
                $goods_addcategory = Db::name('goods_addcategory')
                    ->where($map)
                    ->select();

                foreach ($goods_addcategory as $key => $v)
                {
                   $carId[] = $v['gid'];
                }
            $carId = array_unique($carId);

            $order = 'create_time desc';
        }else{
            $gid = Db::name('goods_addcategory')->where('category_id',$category)->column('gid');
            $carId = array_unique($gid);
        }

        $where['status'] = ['eq',0];
        if ($carId)
            $where['id'] = ['in',$carId];

        $goods = Db::name('goods')
            ->field($field)
            ->where($where)
            ->order($order)
            ->paginate($limit,false,['page' => $page]);
        $list = $goods->items();

        if (empty($list))
        {
            unset($where['is_new']);
            $goods = Db::name('goods')
                ->field($field)
                ->where($where)
                ->order($order)
                ->paginate($limit,false,['page' => $page]);
            $list = $goods->items();
        }
        $goodslist = $userModel->goodsprice($uid,$list);

        $data = [
            'count' => $goods->total(),
            'list'  => $goodslist
        ];
        return $data;
    }

    public function getNewTreeList($pid ,$node = [])
    {
        $vehicle = Db::name('vehicle')->where('id',$pid)->find();
        if ($vehicle['pid'] != 0 && $vehicle['level'] != 1)
        {
            return $this->ordinary($vehicle['pid']);
        }

        $node = $vehicle['id'];
        return $node;
    }

}